// 获取DOM元素
const storyForm = document.getElementById('story-form');
const resultsSection = document.getElementById('results');
const loadingState = document.getElementById('loading-state');
const errorState = document.getElementById('error-state');
const errorMessage = document.getElementById('error-message');
const storyContent = document.getElementById('story-content');
const imagePromptsGrid = document.getElementById('image-prompts-grid');
const promptModal = document.getElementById('prompt-modal');
const promptNumber = document.getElementById('prompt-number');
const promptContent = document.getElementById('prompt-content');
const copyStoryBtn = document.getElementById('copy-story-btn');
const copyPromptBtn = document.getElementById('copy-prompt-btn');
const closeModalBtn = document.getElementById('close-modal-btn');
const navbar = document.getElementById('navbar');

// 图片相关DOM元素
const generateImagesBtn = document.getElementById('generate-images-btn');
const imagesGrid = document.getElementById('images-grid');
const imagesLoadingState = document.getElementById('images-loading-state');
const imagesErrorState = document.getElementById('images-error-state');
const imagesErrorMessage = document.getElementById('images-error-message');

// 故事绘本整合视图相关DOM元素
const generateStorybookBtn = document.getElementById('generate-storybook-btn');
const storybookContainer = document.getElementById('storybook-container');
const storybookInfo = document.getElementById('storybook-info');
const integratedStoryTitle = document.getElementById('integrated-story-title');
const integratedContent = document.getElementById('integrated-content');
const downloadStorybookBtn = document.getElementById('download-storybook-btn');

// 保存当前生成的图片URL
let currentImageUrl = '';

// 禁用生成图片按钮，直到故事生成完成
generateImagesBtn.disabled = true;


// 当前选中的提示词
let currentPrompt = '';
let currentPromptIndex = 0;

// 保存当前生成的提示词列表
let currentImagePrompts = [];

// 后端API基础URL
const API_BASE_URL = 'http://localhost:8000';

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    // 表单提交事件处理
    storyForm.addEventListener('submit', handleFormSubmit);
    
    // 复制故事按钮事件处理
    copyStoryBtn.addEventListener('click', copyStoryContent);
    
    // 模态框关闭按钮事件处理
    closeModalBtn.addEventListener('click', closeModal);
    
    // 复制提示词按钮事件处理
    copyPromptBtn.addEventListener('click', copyCurrentPrompt);
    
    // 点击模态框背景关闭模态框
    promptModal.addEventListener('click', (e) => {
        if (e.target === promptModal) {
            closeModal();
        }
    });
    
    // 滚动事件监听，实现导航栏样式变化
    window.addEventListener('scroll', handleScroll);
    
    // 平滑滚动
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 80,
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // 页面加载时自动从output目录获取数据
    loadOutputData();
    
    // 添加故事绘本整合视图相关事件监听
    generateStorybookBtn.addEventListener('click', generateStorybookView);
    downloadStorybookBtn.addEventListener('click', downloadStorybook);
});

// 从output目录获取数据
async function loadOutputData() {
    try {
        // 添加时间戳防止缓存
        const response = await fetch(`${API_BASE_URL}/api/output-data?t=${new Date().getTime()}`);
        
        if (response.ok) {
            const data = await response.json();
            
            // 如果有数据，显示结果
            if (data.success && (data.story_content || data.image_prompts.length > 0)) {
                resultsSection.classList.remove('hidden');
                
                // 显示故事内容
                if (data.story_content) {
                    storyContent.textContent = data.story_content;
                }
                
                // 显示插画提示词
                if (data.image_prompts.length > 0) {
                    // 保存提示词以便后续使用
                    currentImagePrompts = data.image_prompts;
                    
                    // 只保留第一条提示词，与后端保持一致
                    if (currentImagePrompts.length > 1) {
                        currentImagePrompts = [currentImagePrompts[0]];
                    }
                    
                    // 启用生成图片按钮
                    generateImagesBtn.disabled = false;
                    
                    // 显示插画提示词
                    displayImagePrompts(data.image_prompts);
                    
                    // 如果图片已存在，直接显示
                    if (data.image_exists) {
                        // 提取关键词（简单地从提示词中提取前几个有意义的词）
                        const prompt = currentImagePrompts[0];
                        const keywords = prompt.split(' ').slice(0, 3).join(' ');
                        
                        // 显示关键词
                        const keywordDisplay = document.getElementById('keyword-display');
                        const keywordText = document.getElementById('keyword-text');
                        keywordText.textContent = keywords;
                        keywordDisplay.classList.remove('hidden');
                        
                        // 使用output文件夹中的本地图片，添加时间戳防止浏览器缓存
                        const imageUrl = `../output/story_image.png.png?t=${new Date().getTime()}`;
                        
                        // 保存当前图片URL
                        currentImageUrl = imageUrl;
                        
                        // 创建图片容器，确保居中显示
                        const imageContainer = document.createElement('div');
                        imageContainer.className = 'flex flex-col items-center';
                        
                        // 创建图片卡片，更大的尺寸并居中
                        const imageCard = document.createElement('div');
                        imageCard.className = 'bg-white rounded-xl shadow-lg overflow-hidden transition-all duration-500 hover:shadow-xl max-w-2xl w-full';
                        imageCard.innerHTML = `
                            <div class="relative">
                                <img src="${imageUrl}" alt="故事插画" class="w-full h-auto transition-transform duration-700 hover:scale-105">
                                <div class="absolute top-4 right-4 bg-white/80 backdrop-blur-sm rounded-full p-3 cursor-pointer hover:bg-white transition-colors" data-image-url="${imageUrl}">
                                    <i class="fa fa-download text-gray-700 text-xl"></i>
                                </div>
                            </div>
                            <div class="p-6">
                                <div class="text-lg font-medium text-secondary mb-2">故事插画</div>
                                <p class="text-gray-700">${prompt}</p>
                            </div>
                        `;
                        
                        // 添加下载功能
                        const downloadBtn = imageCard.querySelector('.fa-download').parentElement;
                        downloadBtn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            const url = e.currentTarget.getAttribute('data-image-url');
                            downloadImage(url, `story_image.png.png`);
                        });
                        
                        // 添加到容器
                        imageContainer.appendChild(imageCard);
                        imagesGrid.appendChild(imageContainer);
                    }
                }
            }
        }
    } catch (error) {
        console.error('获取output目录数据失败:', error);
        // 静默失败，不影响用户体验
    }
}

// 处理表单提交
async function handleFormSubmit(e) {
    e.preventDefault();
    
    // 清空之前的结果数据
    currentImagePrompts = [];
    storyContent.textContent = '';
    imagePromptsGrid.innerHTML = '';
    imagesGrid.innerHTML = '';
    document.getElementById('keyword-display').classList.add('hidden');
    
    // 显示加载状态
    resultsSection.classList.remove('hidden');
    loadingState.classList.remove('hidden');
    errorState.classList.add('hidden');
    
    // 收集表单数据
    const formData = new FormData(storyForm);
    const storyParams = {
        theme: formData.get('theme'),
        main_character: formData.get('main_character'),
        setting: formData.get('setting'),
        moral: formData.get('moral') || ''
    };
    
    try {
        // 调用后端API生成故事绘本
        const response = await fetch(`${API_BASE_URL}/api/storybook-generator`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(storyParams)
        });
        
        if (!response.ok) {
            throw new Error('生成故事绘本失败，请稍后重试');
        }
        
        const data = await response.json();
        
        // 隐藏加载状态
        loadingState.classList.add('hidden');
        
        // 显示故事内容
        storyContent.textContent = data.story_content;
        
        // 保存提示词以便后续使用
            currentImagePrompts = data.image_prompts;
            
            // 只保留第一条提示词，与后端保持一致
            if (currentImagePrompts.length > 1) {
                currentImagePrompts = [currentImagePrompts[0]];
            }
            
            // 启用生成图片按钮
            generateImagesBtn.disabled = false;
            
            // 显示插画提示词
            displayImagePrompts(data.image_prompts);
            
            // 滚动到结果区域
            window.scrollTo({
                top: resultsSection.offsetTop - 80,
                behavior: 'smooth'
            });
            
            // 如果已经生成了图片，显示图片
            if (data.image_exists && data.image_path) {
                // 提取关键词（简单地从提示词中提取前几个有意义的词）
                const prompt = currentImagePrompts[0];
                const keywords = prompt.split(' ').slice(0, 3).join(' ');
                
                // 显示关键词
                const keywordDisplay = document.getElementById('keyword-display');
                const keywordText = document.getElementById('keyword-text');
                keywordText.textContent = keywords;
                keywordDisplay.classList.remove('hidden');
                
                // 使用output文件夹中的本地图片，添加时间戳防止浏览器缓存
                        const imageUrl = `../output/story_image.png.png?t=${new Date().getTime()}`;
                        
                        // 保存当前图片URL
                        currentImageUrl = imageUrl;
                        
                        // 创建图片容器，确保居中显示
                        const imageContainer = document.createElement('div');
                        imageContainer.className = 'flex flex-col items-center';
                
                // 创建图片卡片，更大的尺寸并居中
                const imageCard = document.createElement('div');
                imageCard.className = 'bg-white rounded-xl shadow-lg overflow-hidden transition-all duration-500 hover:shadow-xl max-w-2xl w-full';
                imageCard.innerHTML = `
                    <div class="relative">
                        <img src="${imageUrl}" alt="故事插画" class="w-full h-auto transition-transform duration-700 hover:scale-105">
                        <div class="absolute top-4 right-4 bg-white/80 backdrop-blur-sm rounded-full p-3 cursor-pointer hover:bg-white transition-colors" data-image-url="${imageUrl}">
                            <i class="fa fa-download text-gray-700 text-xl"></i>
                        </div>
                    </div>
                    <div class="p-6">
                        <div class="text-lg font-medium text-secondary mb-2">故事插画</div>
                        <p class="text-gray-700">${prompt}</p>
                    </div>
                `;
                
                // 添加下载功能
                const downloadBtn = imageCard.querySelector('.fa-download').parentElement;
                downloadBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    const url = e.currentTarget.getAttribute('data-image-url');
                    downloadImage(url, `story_image.png.png`);
                });
                
                // 添加到容器
                imageContainer.appendChild(imageCard);
                imagesGrid.appendChild(imageContainer);
            }
            
        } catch (error) {
            // 显示错误状态
            loadingState.classList.add('hidden');
            errorState.classList.remove('hidden');
            errorMessage.textContent = error.message || '生成故事绘本时发生错误，请重试';
        }
}

// 显示插画提示词
function displayImagePrompts(prompts) {
    // 清空现有提示词
    imagePromptsGrid.innerHTML = '';
    
    // 创建提示词卡片并添加到网格中
    prompts.forEach((prompt, index) => {
        const promptCard = document.createElement('div');
        promptCard.className = 'prompt-card bg-white rounded-xl shadow-md p-6 cursor-pointer transition-all duration-300';
        
        // 创建提示词卡片内容
        const promptNumberEl = document.createElement('div');
        promptNumberEl.className = 'text-sm text-primary font-semibold mb-2';
        promptNumberEl.textContent = `提示词 ${index + 1}`;
        
        const promptPreviewEl = document.createElement('div');
        promptPreviewEl.className = 'text-gray-700 line-clamp-3';
        promptPreviewEl.textContent = prompt;
        
        const viewMoreEl = document.createElement('div');
        viewMoreEl.className = 'mt-3 text-primary text-sm font-medium flex items-center';
        viewMoreEl.innerHTML = '查看详情 <i class="fa fa-arrow-right ml-1"></i>';
        
        // 将元素添加到卡片中
        promptCard.appendChild(promptNumberEl);
        promptCard.appendChild(promptPreviewEl);
        promptCard.appendChild(viewMoreEl);
        
        // 添加点击事件，显示提示词详情
        promptCard.addEventListener('click', () => {
            openPromptModal(prompt, index + 1);
        });
        
        // 将卡片添加到网格中
        imagePromptsGrid.appendChild(promptCard);
    });
}

// 打开提示词详情模态框
function openPromptModal(prompt, index) {
    currentPrompt = prompt;
    currentPromptIndex = index;
    
    promptNumber.textContent = `提示词 ${index}`;
    promptContent.textContent = prompt;
    
    promptModal.classList.remove('hidden');
    // 防止页面滚动
    document.body.style.overflow = 'hidden';
}

// 关闭提示词详情模态框
function closeModal() {
    promptModal.classList.add('hidden');
    // 恢复页面滚动
    document.body.style.overflow = 'auto';
}

// 复制故事内容
function copyStoryContent() {
    const textToCopy = storyContent.textContent;
    navigator.clipboard.writeText(textToCopy)
        .then(() => {
            showNotification('故事内容已复制到剪贴板');
        })
        .catch(err => {
            console.error('复制失败:', err);
            showNotification('复制失败，请手动复制', 'error');
        });
}

// 复制当前提示词
function copyCurrentPrompt() {
    navigator.clipboard.writeText(currentPrompt)
        .then(() => {
            showNotification('提示词已复制到剪贴板');
        })
        .catch(err => {
            console.error('复制失败:', err);
            showNotification('复制失败，请手动复制', 'error');
        });
}

// 显示通知
function showNotification(message, type = 'success') {
    // 检查是否已存在通知元素
    let notification = document.querySelector('.notification');
    
    if (notification) {
        // 如果已存在，更新内容
        notification.textContent = message;
        notification.className = `notification fixed top-20 right-4 px-6 py-3 rounded-lg shadow-lg transform transition-all duration-300 z-50 ${type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'}`;
    } else {
        // 创建新的通知元素
        notification = document.createElement('div');
        notification.className = `notification fixed top-20 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-x-full transition-all duration-300 z-50 ${type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'}`;
        notification.textContent = message;
        document.body.appendChild(notification);
        
        // 显示通知
        setTimeout(() => {
            notification.classList.remove('translate-x-full');
        }, 10);
    }
    
    // 3秒后自动隐藏通知
    setTimeout(() => {
        if (notification) {
            notification.classList.add('translate-x-full');
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }
    }, 3000);
}

// 处理滚动事件，改变导航栏样式
function handleScroll() {
    if (window.scrollY > 50) {
        navbar.classList.add('py-2', 'bg-white/95', 'backdrop-blur-sm');
        navbar.classList.remove('py-3', 'bg-white');
    } else {
        navbar.classList.add('py-3', 'bg-white');
        navbar.classList.remove('py-2', 'bg-white/95', 'backdrop-blur-sm');
    }
}

// 添加键盘事件监听，ESC关闭模态框
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && !promptModal.classList.contains('hidden')) {
        closeModal();
    }
});

// 添加动画效果，当元素进入视口时显示
const animateOnScroll = () => {
    const elements = document.querySelectorAll('.animate-on-scroll');
    
    elements.forEach(element => {
        const elementPosition = element.getBoundingClientRect().top;
        const screenPosition = window.innerHeight / 1.2;
        
        if (elementPosition < screenPosition) {
            element.classList.add('animate-fade-in');
        }
    });
};

// 添加滚动监听，实现元素动画
window.addEventListener('scroll', animateOnScroll);

// 生成图片的函数
async function generateImages() {
    if (!currentImagePrompts || currentImagePrompts.length === 0) {
        showNotification('请先生成故事绘本以获取插画提示词', 'error');
        return;
    }
    
    // 清空之前的图片
    imagesGrid.innerHTML = '';
    
    // 显示加载状态
    imagesLoadingState.classList.remove('hidden');
    imagesErrorState.classList.add('hidden');
    generateImagesBtn.disabled = true;
    generateImagesBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i><span>生成中...</span>';
    
    try {
        // 只使用第一条提示词生成图片（按照storybook_generator.py的逻辑）
        const prompt = currentImagePrompts[0];
        
        // 提取关键词（简单地从提示词中提取前几个有意义的词）
        const keywords = prompt.split(' ').slice(0, 3).join(' ');
        
        // 显示关键词
        const keywordDisplay = document.getElementById('keyword-display');
        const keywordText = document.getElementById('keyword-text');
        keywordText.textContent = keywords;
        keywordDisplay.classList.remove('hidden');
        
        // 模拟图片生成延迟
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 使用output文件夹中的本地图片，添加时间戳防止浏览器缓存
        const imageUrl = `../output/story_image.png.png?t=${new Date().getTime()}`; // 匹配实际生成的双.png扩展名文件
        
        // 创建图片容器，确保居中显示
        const imageContainer = document.createElement('div');
        imageContainer.className = 'flex flex-col items-center';
        
        // 创建图片卡片，更大的尺寸并居中
        const imageCard = document.createElement('div');
        imageCard.className = 'bg-white rounded-xl shadow-lg overflow-hidden transition-all duration-500 hover:shadow-xl max-w-4xl w-full';
        imageCard.innerHTML = `
            <div class="relative">
                <img src="${imageUrl}" alt="故事插画" class="w-full h-auto max-h-[500px] object-contain transition-transform duration-700 hover:scale-105">
                <div class="absolute top-4 right-4 bg-white/80 backdrop-blur-sm rounded-full p-3 cursor-pointer hover:bg-white transition-colors" data-image-url="${imageUrl}">
                    <i class="fa fa-download text-gray-700 text-xl"></i>
                </div>
            </div>
            <div class="p-6">
                <div class="text-xl font-medium text-secondary mb-2">故事插画</div>
                <p class="text-gray-700 text-lg">${prompt}</p>
            </div>
        `;
        
        // 添加下载功能
        const downloadBtn = imageCard.querySelector('.fa-download').parentElement;
        downloadBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            const url = e.currentTarget.getAttribute('data-image-url');
            downloadImage(url, `story_image.png.png`); // 与后端保持一致，使用双.png扩展名
        });
        
        // 添加到容器
        imageContainer.appendChild(imageCard);
        imagesGrid.appendChild(imageContainer);
        
        showNotification('插画生成完成！', 'success');
    } catch (error) {
        // 显示错误状态
        imagesLoadingState.classList.add('hidden');
        imagesErrorState.classList.remove('hidden');
        imagesErrorMessage.textContent = `生成插画失败: ${error.message || '未知错误'}`;
    } finally {
        // 恢复按钮状态
        imagesLoadingState.classList.add('hidden');
        generateImagesBtn.disabled = false;
        generateImagesBtn.innerHTML = '<i class="fa fa-magic"></i><span>生成插画</span>';
    }
}

// 下载图片函数
function downloadImage(url, filename) {
    // 创建一个临时的a标签用于下载
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    
    // 添加到文档并触发点击
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    
    showNotification(`图片已下载: ${filename}`, 'success');
}

// 添加图片生成按钮的事件监听器
generateImagesBtn.addEventListener('click', generateImages);

// 生成故事绘本整合视图
function generateStorybookView() {
    // 检查是否有故事内容和图片
    const storyText = storyContent.textContent.trim();
    
    if (!storyText) {
        showNotification('请先生成故事内容', 'error');
        return;
    }
    
    if (!currentImageUrl) {
        showNotification('请先生成插画', 'error');
        return;
    }
    
    // 隐藏提示信息，显示整合视图容器
    storybookInfo.classList.add('hidden');
    storybookContainer.classList.remove('hidden');
    
    // 设置故事标题（从故事内容提取第一句话作为标题）
    const storyTitle = extractStoryTitle(storyText);
    integratedStoryTitle.textContent = storyTitle;
    
    // 清空之前的整合内容
    integratedContent.innerHTML = '';
    
    // 将故事内容分段并与图片整合显示
    const paragraphs = splitStoryIntoParagraphs(storyText);
    
    // 创建内容部分
    paragraphs.forEach((paragraph, index) => {
        // 为每个段落创建一个容器
        const sectionContainer = document.createElement('div');
        sectionContainer.className = 'flex flex-col md:flex-row items-center gap-8';
        
        // 决定图片和文本的顺序（交替显示）
        if (index % 2 === 0) {
            // 图片在左，文本在右
            sectionContainer.innerHTML = `
                <div class="md:w-1/2">
                    <div class="rounded-xl overflow-hidden shadow-lg">
                        <img src="${currentImageUrl}" alt="故事插画" class="w-full h-[300px] object-contain">
                    </div>
                </div>
                <div class="md:w-1/2 prose prose-xl max-w-none text-gray-700 text-indent-4 font-song">
                    ${paragraph}
                </div>
            `;
        } else {
            // 文本在左，图片在右
            sectionContainer.innerHTML = `
                <div class="md:w-1/2 prose prose-xl max-w-none text-gray-700 text-indent-4 font-song order-2 md:order-1">
                    ${paragraph}
                </div>
                <div class="md:w-1/2 order-1 md:order-2">
                    <div class="rounded-xl overflow-hidden shadow-lg">
                        <img src="${currentImageUrl}" alt="故事插画" class="w-full h-[300px] object-contain">
                    </div>
                </div>
            `;
        }
        
        // 添加到整合内容区域
        integratedContent.appendChild(sectionContainer);
        
        // 在段落之间添加分隔线
        if (index < paragraphs.length - 1) {
            const divider = document.createElement('div');
            divider.className = 'w-16 h-1 bg-gray-200 mx-auto';
            integratedContent.appendChild(divider);
        }
    });
    
    // 滚动到整合视图区域
    window.scrollTo({
        top: document.getElementById('storybook-integration').offsetTop - 100,
        behavior: 'smooth'
    });
    
    showNotification('故事绘本整合视图生成完成！', 'success');
}

// 从故事内容提取标题（取书名号中的内容）
function extractStoryTitle(storyText) {
    // 查找书名号中的内容
    const bookTitleStart = storyText.indexOf('《');
    const bookTitleEnd = storyText.indexOf('》');
    
    // 如果找到书名号，则提取其中的内容作为标题
    if (bookTitleStart !== -1 && bookTitleEnd !== -1 && bookTitleEnd > bookTitleStart) {
        return storyText.substring(bookTitleStart, bookTitleEnd + 1).trim();
    }
    
    // 如果没有找到书名号，则查找第一个句号、问号或感叹号
    const firstSentenceEnd = Math.min(
        storyText.indexOf('。') + 1 || storyText.length,
        storyText.indexOf('？') + 1 || storyText.length,
        storyText.indexOf('！') + 1 || storyText.length
    );
    
    // 提取标题，如果太短则使用默认标题
    let title = storyText.substring(0, firstSentenceEnd).trim();
    if (title.length < 5) {
        title = '童话故事';
    }
    
    return title;
}

// 将故事内容分段
function splitStoryIntoParagraphs(storyText) {
    // 使用句号、问号、感叹号作为分段标记
    const paragraphs = [];
    let currentParagraph = '';
    let i = 0;
    
    while (i < storyText.length) {
        currentParagraph += storyText[i];
        
        // 遇到结束符且后面没有内容或后面是换行符/空格，进行分段
        if ((storyText[i] === '。' || storyText[i] === '？' || storyText[i] === '！') && 
            (i === storyText.length - 1 || 
             storyText[i + 1] === '\n' || 
             storyText[i + 1] === '\r' || 
             storyText[i + 1] === ' ')) {
            paragraphs.push(currentParagraph.trim());
            currentParagraph = '';
        }
        
        i++;
    }
    
    // 如果最后还有内容没有分段
    if (currentParagraph.trim()) {
        paragraphs.push(currentParagraph.trim());
    }
    
    // 如果段落太少（少于3段），合并一些段落
    if (paragraphs.length > 0) {
        const result = [];
        let temp = '';
        
        for (let j = 0; j < paragraphs.length; j++) {
            temp += paragraphs[j] + ' ';
            
            // 每2-3段合并为一个大段落（根据总段落数调整）
            if (paragraphs.length <= 3 || j % Math.ceil(paragraphs.length / 3) === Math.ceil(paragraphs.length / 3) - 1) {
                result.push(temp.trim());
                temp = '';
            }
        }
        
        if (temp.trim()) {
            result.push(temp.trim());
        }
        
        return result;
    }
    
    return [storyText];
}

// 下载故事绘本（简单实现，实际项目中可能需要更复杂的PDF生成功能）
function downloadStorybook() {
    showNotification('故事绘本下载功能正在开发中，敬请期待！', 'info');
    
    // 这里是一个简单的实现，实际项目中可能需要使用canvas或第三方库将内容转换为PDF
    // 目前只提供复制功能作为替代
    const storyText = storyContent.textContent.trim();
    if (storyText) {
        navigator.clipboard.writeText(storyText)
            .then(() => {
                showNotification('故事内容已复制到剪贴板，您可以手动保存', 'success');
            })
            .catch(err => {
                console.error('复制失败:', err);
                showNotification('复制失败，请手动复制', 'error');
            });
    }
}

// 初始化时检查一次
animateOnScroll();